/**
 * 系统管理 用户管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="">
        <el-input size="small" v-model="formInline.username" placeholder="输入用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()"  v-if="sys_user_add">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" @selection-change="selectChange" :data="list" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>
      <el-table-column align="center"  prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column align="center"  prop="phone" label="手机号" width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="createTime" label="创建时间" min-width="120">
      </el-table-column>
      <el-table-column align="center"  prop="deptId" label="部门" min-width="120">
        <template slot-scope="scope">
          {{scope.row.deptName}}
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="lockFlag" label="状态" min-width="50">
        <template slot-scope="scope">
          <el-switch disabled="" v-model="scope.row.lockFlag=='0'?nshow:fshow" active-color="#13ce66" inactive-color="#ff4949" @change="editType(scope.$index, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="50">
        <template slot-scope="scope">
          <el-button v-if="sys_user_edit"
                     size="small"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleEdit(scope.row,scope.index)">编辑
          </el-button>
          <el-button v-if="sys_user_del"
                     size="small"
                     type="text"
                     icon="el-icon-delete"
                     @click="deletes(scope.row,scope.index)">删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="page" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
        <!--<el-input size="small"  hidden v-model="editForm.userId" ></el-input>-->
        <el-form-item label="用户名" prop="username">
          <el-input size="small" v-model="editForm.username" auto-complete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="角色" >
          <el-checkbox-group v-model="editForm.role" >
            <el-checkbox
              v-for="item in rolesOptions"
              :label="item.roleId"
              :value="item.roleId"
              :key="item.roleId">
              {{item.roleName}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input size="small" v-model="editForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input size="small" v-model="editForm.password" placeholder="请输入新密码"></el-input>
        </el-form-item>

        <el-form-item label="部门" prop="deptId">
        <el-tree :data="treeDeptData" ref="tree"  show-checkbox default-expand-all check-strictly node-key="id" :default-checked-keys="currentDept"   :props="deptProps" @check-change="handleNodeClick"></el-tree>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title"  @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {addObj, delObj, fetchList, putObj} from "@/api/admin/user";
import {deptRoleList} from "@/api/admin/role";
import {fetchTree} from "@/api/admin/dept";
import {mapGetters} from "vuex";
import Pagination from '../../../components/Pagination'
export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      title: '添加用户',
      editFormVisible: false, //控制编辑页面显示与隐藏
      deptProps: {
        children: 'children',
        label: 'name'

      },
      resourceCheckedKey:'',
      unitAccessshow: false, //控制所属单位隐藏与显示
      // 编辑与添加
      editForm: {
        userId: '',
        username: '',
        role: [],
        phone: '',
        password: '',
        deptId: '',
      },
      rolesOptions: [],



      // 选择数据
      selectdata: [],
      // rules表单验证
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            required: true,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      },
      // 请求数据参数
      formInline: {
        username: '',

      },
      //用户数据
      // 数据权限
      treeDeptData: [],
      currentDept:[],

      //参数role
      saveroleId: '',
      // 分页参数
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false//是否倒序
      },
      list: [],
   //   loading: true,

    }
  },
  // 注册组件
  components: {
    Pagination
  },

  /**
   * 数据发生改变
   */
  watch: {},


  computed: {
    ...mapGetters(["permissions"])
  },
  /**
   * 创建完毕
   */
  created() {
    this.sys_user_add = this.permissions["sys_user_add"];
    this.sys_user_edit = this.permissions["sys_user_edit"];
    this.sys_user_del = this.permissions["sys_user_del"];
    this.getDataList();
    this.getNodeData();
    this.handleDept();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    getNodeData() {
      deptRoleList().then(response => {
        this.rolesOptions = response.data.data;
      });
    },
    handleDept() {
      fetchTree().then(response => {
        this.treeDeptData = response.data.data;
      });
    },
    getDataList() {
      this.loading = true;
      fetchList(Object.assign({
        current: this.page.currentPage,
        size: this.page.pageSize
      }, this.formInline)).then(response => {

        this.list = response.data.data.records;

        this.page.total = response.data.data.total
        this.loading = false;
      });
    },
    // 分页插件事件
    callFather(parm) {
      this.page.currentPage = parm.currentPage
      this.page.pageSize = parm.pageSize
      this.getDataList()
    //  this.getdata(this.formInline)
    },
    //搜索事件
    search() {
      this.getDataList()
    //  this.getdata(this.formInline)
    },
    handleNodeClick(data, checked, indeterminate) {
      if (checked) {
        let arr = [data.id];
        this.$refs.tree.setCheckedKeys(arr);
        this.editForm.deptId = data.id;

      }
    },
    //显示编辑界面
    handleEdit: function(row,index ) {
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改用户'
        this.editForm.userId = row.userId
        this.editForm.username = row.username
        this.editForm.phone = row.phone
        var roleList =new Array()
        for(var j = 0; j < row.roleList.length; j++) {
          roleList.push(row.roleList[j].roleId);
        }
        this.editForm.role = roleList;
        this.editForm.deptId = row.deptId;
        this.currentDept = [];
        this.currentDept.push(this.editForm.deptId)
      } else {
        this.title = '添加用户'
        this.editForm.userId = ''
        this.editForm.username = ''
        this.editForm.phone = ''
        this.currentDept = [];
        this.editForm.role = [];
        this.editForm.deptId = '';
        this.currentDept = [];
      }

    },
    // 编辑、添加提交方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {

        if (valid) {
          if(this.editForm.userId == ''){
            addObj(this.editForm).then(() => {
              this.getDataList(this.page);
              this.$message({type: 'success', message: '数据保存成功！'})
              this.editFormVisible = false;
            }).catch((e) => {
            //  this.$message.error('数据保存失败,请稍后再试！')
            });

          }else{
            putObj(this.editForm).then(() => {
              this.getDataList(this.page);
              this.$message({type: 'success', message: '数据保存成功！'})
              this.editFormVisible = false;
            }).catch((e) => {
            });
          }
        } else {
          return false
        }
      })
    },


    // 选择复选框事件
    selectChange(val) {
      this.selectdata = val
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == 'edit') {
        this.editFormVisible = false
      } else if (dialog == 'perm') {
        this.dataAccessshow = false
      } else if (dialog == 'unit') {
        this.unitAccessshow = false
      }
    },
    // 删除用户
    deletes(row, index) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delObj(row.userId).then(() => {
            this.getDataList(this.page);
            this.$notify.success('删除成功')
          }).catch(() => {
            this.$notify.error('删除失败')
          });
        })
        .catch((e) => {
          console.log(e)
          this.$message({
            type: 'info',
            message: '已取消删除！'
          })
        })
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

